package RoleService

import (
	"database/sql"
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/internal/service/BaseService"
	"seawolf-admin-go/utility/MyCfg"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
	"strings"
	"time"
)

func List(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	condition := g.Map{}
	obj := db.GetUnSafaTable(ctx, req.TableName)
	// 默认全部表别名先设置为 a
	asName := "a"
	// 处理查询的列
	selectFields := ""
	defaultSelectFields := strings.Split(obj.GetFieldsStr(), ",")

	listQueryOp := req.ListQueryOp
	if listQueryOp != nil {
		if listQueryOp.AsName != "" {
			asName = listQueryOp.AsName
		}
	}
	// 有设置表别名
	obj.As(asName)
	// 获取查询条件
	BaseService.GetCondition(r, condition, listQueryOp, asName)

	condition["is_org"] = 1

	obj.Where(
		condition,
	)

	if listQueryOp != nil {
		if len(listQueryOp.SelectFields) > 0 {
			// 设置了 select 的
			selectFields = strings.Join(listQueryOp.SelectFields, ",")
		}
		if listQueryOp.OrderBy != "" {
			obj.Order(listQueryOp.OrderBy)
		}
	}
	// 设置 select
	if selectFields != "" {
		obj.Fields(selectFields)
	} else {
		for k, v := range defaultSelectFields {
			defaultSelectFields[k] = asName + "." + v
		}
		obj.Fields(strings.Join(defaultSelectFields, ","))
	}
	// 处理查询里 --- end ---

	if listQueryOp != nil {
		if listQueryOp.IsCache > 0 && MyCfg.GetSiteConfig[bool](ctx, "BaseCacheIsOpen") {
			// 开启了缓存
			obj.Cache(gdb.CacheOption{
				Name: "backCache:" + req.TableName + ":list:" + gmd5.MustEncrypt(condition),
				// 缓存时间
				Duration: time.Duration(listQueryOp.IsCache) * time.Second,
			})
		}
		for _, item := range listQueryOp.LeftJoin {
			obj.LeftJoin(item.TableInfo, item.Condition)
		}
	}

	if req.SoftDeleteField != "" {
		obj.Where(asName+"."+req.SoftDeleteField, 0)
	}

	res, err := obj.All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	return response.SuccessByRequestMessageData(nil, "获取成功",
		res.List())
}
